package com.sun.controller;

import com.sun.dto.UserDTO;
import com.sun.pojo.User;
import com.sun.service.UserService;
import com.sun.utils.PageBean;
import com.sun.utils.Paying;
import com.sun.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService<User> userService;



    @PostMapping("/userList")
    public Result<List<UserDTO>> getUserList(Integer pageSize, Integer pageNo ,@RequestBody UserDTO userDTO){
        Result<List<UserDTO>> result = new Result<>();
        if (pageSize == null || pageNo == null){
            return result;
        }
        PageBean<User> userPageBean = new PageBean<>();
        // 1. 获取总行数
        int rows = userService.getRowsByUserDTO(userDTO);
        if (rows < 1){
            return result;
        }
        PageBean<User> pageBean = userPageBean.initiallze(pageSize, pageNo, rows);
        // 2. 初始化查询对象
        Paying<User> paying = new Paying<>();
        paying.setObject(userDTO);
        paying.setPageBean(userPageBean);
        int offset = (pageBean.getPageNo() - 1) * pageBean.getPageSize();
        paying.setOffset(offset);
        paying.setLimit(pageBean.getPageSize());
        List<User> userListByPaying = userService.getUserListByPaying(paying);
        List<UserDTO> userDTOS = new ArrayList<>();
        userListByPaying.forEach(x -> {
            userDTOS.add(x.convert(x));
        });
        result.setData(userDTOS);
        result.setMsg("success");
        result.setState(true);
        return result;
    }
}
